# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
        def dfs(treeNode, listNode):
            if listNode is None:
                return True
            if treeNode is None:
                return False
            if treeNode.val != listNode.val:
                return False
            return dfs(treeNode.left, listNode.next) or dfs(
                treeNode.right, listNode.next)

        stack = []
        stack.append(root)
        while stack:
            node = stack.pop()
            if dfs(node, head):
                return True
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)

        return False
